<template>
  <Modal
    :open="visible"
    :title="isEdit ? '编辑权限' : '新增权限'"
    :confirm-loading="confirmLoading"
    width="700px"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <Form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 18 }"
    >
      <!-- 权限编码 -->
      <FormItem label="权限编码" name="permissionCode">
        <Input
          v-model:value="formData.permissionCode"
          :disabled="selectedMenuKeys.length > 0"
          placeholder="如：sys:user:add, sys:user:edit, sys:user:delete"
        >
          <template #addonBefore>
            <Tooltip
              title="权限编码规范：服务名缩写:模块:操作，如 sys:user:add"
            >
              <InfoCircleOutlined />
            </Tooltip>
          </template>
        </Input>
        <div class="form-tip" v-if="selectedMenuKeys.length > 0">
          <strong style="color: #52c41a;">✓ 提示：</strong>已选择菜单，权限编码自动从菜单带入，不可手动修改
        </div>
        <div class="form-tip" v-else>
          <strong style="color: #faad14;">⚠ 提示：</strong>未选择菜单时，可以手动输入权限编码
        </div>
      </FormItem>

      <!-- 权限名称 -->
      <FormItem label="权限名称" name="permissionName">
        <Input
          v-model:value="formData.permissionName"
          placeholder="如：新增用户、编辑用户、删除用户"
        />
      </FormItem>

      <!-- 权限类型 -->
      <FormItem label="权限类型" name="permissionType">
        <RadioGroup
          v-model:value="formData.permissionType"
          :disabled="selectedMenuKeys.length > 0"
        >
          <Radio :value="PermissionType.URL">接口权限</Radio>
          <Radio :value="PermissionType.BUTTON">按钮权限</Radio>
        </RadioGroup>
        <div class="form-tip" v-if="selectedMenuKeys.length > 0">
          <strong style="color: #52c41a;">✓ 提示：</strong>已选择菜单，权限类型根据菜单类型自动设置（目录/菜单→接口权限，按钮→按钮权限）
        </div>
        <div class="form-tip" v-else>
          <strong style="color: #faad14;">⚠ 提示：</strong>未选择菜单时，可以手动选择权限类型
        </div>
      </FormItem>

      <!-- 所属菜单 -->
      <FormItem label="所属菜单" name="menuId">
        <div class="menu-tree-container">
          <!-- 选择状态提示 -->
          <div class="mb-3">
            <div
              v-if="selectedMenuKeys.length > 0"
              class="selected-status-badge"
            >
              <div class="flex items-center gap-2">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  class="h-4 w-4 text-blue-600"
                  viewBox="0 0 20 20"
                  fill="currentColor"
                >
                  <path
                    fill-rule="evenodd"
                    d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                    clip-rule="evenodd"
                  />
                </svg>
                <span class="font-medium text-blue-700">已选择菜单</span>
                <span class="selected-menu-name">{{ getSelectedMenuName() }}</span>
              </div>
              <Button
                size="small"
                danger
                type="link"
                @click="clearMenuSelection"
              >
                清空
              </Button>
            </div>
            <div
              v-else
              class="unselected-status-badge"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                class="h-4 w-4 text-gray-400"
                viewBox="0 0 20 20"
                fill="currentColor"
              >
                <path
                  fill-rule="evenodd"
                  d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
                  clip-rule="evenodd"
                />
              </svg>
              <span class="text-gray-500">未选择菜单</span>
            </div>
          </div>

          <!-- 搜索框 -->
          <div class="mb-3">
            <Input
              v-model:value="searchKeyword"
              placeholder="搜索菜单或按钮名称..."
              allow-clear
              @input="handleSearch"
            >
              <template #prefix>
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  class="h-4 w-4 text-gray-400"
                  viewBox="0 0 20 20"
                  fill="currentColor"
                >
                  <path
                    fill-rule="evenodd"
                    d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z"
                    clip-rule="evenodd"
                  />
                </svg>
              </template>
            </Input>
          </div>

          <!-- 统计信息和操作按钮 -->
          <div class="mb-2 flex items-center justify-between">
            <div class="text-xs text-gray-500">
              <span v-if="searchKeyword">
                找到 {{ extractAllMenuIds(displayMenuTreeData).length }} 个匹配项
              </span>
              <span v-else>
                共 {{ extractAllMenuIds(menuTree).length }} 个节点
              </span>
            </div>
            <div class="flex items-center gap-3">
              <Button size="small" @click="expandedMenuKeys = extractAllMenuIds(displayMenuTreeData)">
                <template #icon>
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    class="h-3.5 w-3.5"
                    viewBox="0 0 20 20"
                    fill="currentColor"
                  >
                    <path
                      fill-rule="evenodd"
                      d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
                      clip-rule="evenodd"
                    />
                  </svg>
                </template>
                展开全部
              </Button>
              <Button size="small" @click="expandedMenuKeys = []">
                <template #icon>
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    class="h-3.5 w-3.5"
                    viewBox="0 0 20 20"
                    fill="currentColor"
                  >
                    <path
                      fill-rule="evenodd"
                      d="M14.707 12.707a1 1 0 01-1.414 0L10 9.414l-3.293 3.293a1 1 0 01-1.414-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 010 1.414z"
                      clip-rule="evenodd"
                    />
                  </svg>
                </template>
                收起全部
              </Button>
            </div>
          </div>

          <!-- 菜单树 -->
          <div class="tree-wrapper">
            <Tree
              v-if="displayMenuTreeData.length > 0"
              :tree-data="displayMenuTreeData"
              :field-names="{
                title: 'menuName',
                key: 'id',
                children: 'children',
              }"
              :selected-keys="selectedMenuKeys"
              :expanded-keys="expandedMenuKeys"
              @select="onMenuSelect"
              @expand="(keys: number[]) => (expandedMenuKeys = keys)"
            >
              <template #title="{ id, menuName, menuType }">
                <div
                  class="menu-node-wrapper"
                  :class="{ 'is-selected': selectedMenuKeys.includes(id) }"
                >
                  <span class="inline-flex items-center gap-2">
                    <!-- 目录 -->
                    <span
                      v-if="menuType === 1"
                      class="menu-icon-wrapper"
                      :class="{ 'selected-icon': selectedMenuKeys.includes(id) }"
                    >
                      <span
                        class="inline-flex h-6 w-6 items-center justify-center rounded-md bg-gradient-to-br from-amber-400 to-orange-500 shadow-sm transition-all"
                      >
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          class="h-3.5 w-3.5 text-white"
                          viewBox="0 0 20 20"
                          fill="currentColor"
                        >
                          <path d="M2 6a2 2 0 012-2h5l2 2h5a2 2 0 012 2v6a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" />
                        </svg>
                      </span>
                    </span>
                    <!-- 菜单 -->
                    <span
                      v-else-if="menuType === 2"
                      class="menu-icon-wrapper"
                      :class="{ 'selected-icon': selectedMenuKeys.includes(id) }"
                    >
                      <span
                        class="inline-flex h-6 w-6 items-center justify-center rounded-md bg-gradient-to-br from-blue-400 to-blue-600 shadow-sm transition-all"
                      >
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          class="h-3.5 w-3.5 text-white"
                          viewBox="0 0 20 20"
                          fill="currentColor"
                        >
                          <path d="M3 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1V4zM3 10a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H4a1 1 0 01-1-1v-6zM14 9a1 1 0 00-1 1v6a1 1 0 001 1h2a1 1 0 001-1v-6a1 1 0 00-1-1h-2z" />
                        </svg>
                      </span>
                    </span>
                    <!-- 按钮 - 使用标签样式 -->
                    <span
                      v-else-if="menuType === 3"
                      class="inline-flex items-center gap-1.5 rounded-full border border-green-300 bg-gradient-to-r from-green-50 to-emerald-50 px-2.5 py-0.5 text-xs font-medium text-green-700 shadow-sm transition-all"
                      :class="{ 'selected-button': selectedMenuKeys.includes(id) }"
                    >
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        class="h-3 w-3"
                        viewBox="0 0 20 20"
                        fill="currentColor"
                      >
                        <path
                          fill-rule="evenodd"
                          d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                          clip-rule="evenodd"
                        />
                      </svg>
                      {{ menuName }}
                    </span>
                    <!-- 非按钮节点显示名称 -->
                    <span
                      v-if="menuType !== 3"
                      class="menu-name"
                      :class="menuType === 1 ? 'font-semibold text-gray-800' : 'text-gray-700'"
                    >
                      {{ menuName }}
                    </span>
                    <!-- 选中标记 -->
                    <span
                      v-if="selectedMenuKeys.includes(id)"
                      class="selected-badge"
                    >
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        class="h-4 w-4"
                        viewBox="0 0 20 20"
                        fill="currentColor"
                      >
                        <path
                          fill-rule="evenodd"
                          d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                          clip-rule="evenodd"
                        />
                      </svg>
                    </span>
                  </span>
                </div>
              </template>
            </Tree>
            <div v-else class="empty-tree">
              <div class="text-gray-400">
                {{ searchKeyword ? '未找到匹配的菜单' : '暂无菜单数据' }}
              </div>
              <div v-if="!searchKeyword" class="mt-1 text-xs text-gray-400">
                请检查菜单树是否加载成功
              </div>
            </div>
          </div>
        </div>
        <div class="form-tip">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            class="inline h-3.5 w-3.5"
            viewBox="0 0 20 20"
            fill="currentColor"
          >
            <path
              fill-rule="evenodd"
              d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
              clip-rule="evenodd"
            />
          </svg>
          关联菜单后，可以在菜单管理中直接使用此权限编码（单击选择，再次单击取消选择）
        </div>
      </FormItem>

      <!-- 接口地址 -->
      <FormItem label="接口地址" name="url">
        <Input
          v-model:value="formData.url"
          placeholder="如：/system/user/add"
        />
        <div class="form-tip">
          <span v-if="formData.permissionType === PermissionType.URL">
            <strong style="color: #ff4d4f;">*</strong> 接口权限必须填写接口地址
          </span>
          <span v-else>
            按钮权限可选填写接口地址，用于 URL 级别的权限控制
          </span>
        </div>
      </FormItem>

      <!-- 请求方法 -->
      <FormItem label="请求方法" name="method">
        <Select v-model:value="formData.method" placeholder="选择请求方法" allow-clear>
          <SelectOption value="GET">GET</SelectOption>
          <SelectOption value="POST">POST</SelectOption>
          <SelectOption value="PUT">PUT</SelectOption>
          <SelectOption value="DELETE">DELETE</SelectOption>
          <SelectOption value="PATCH">PATCH</SelectOption>
        </Select>
        <div class="form-tip">
          <span v-if="formData.permissionType === PermissionType.URL">
            <strong style="color: #ff4d4f;">*</strong> 接口权限必须选择请求方法
          </span>
          <span v-else>
            按钮权限可选择请求方法，配合接口地址使用
          </span>
        </div>
      </FormItem>
    </Form>
  </Modal>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';

import {
  Alert,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Radio,
  RadioGroup,
  Select,
  SelectOption,
  Tooltip,
  Tree,
} from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import { InfoCircleOutlined } from '@ant-design/icons-vue';

import type { RoleMenuTreeNode } from '#/api/core/role';
import type { Permission } from '#/api/core/permission';
import {
  addPermissionApi,
  PermissionType,
  updatePermissionApi,
} from '#/api/core/permission';
import { prepareCreateData, prepareUpdateData } from '#/utils/form';

interface Props {
  visible: boolean;
  permission?: Permission;
  menuTree: RoleMenuTreeNode[];
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'success'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const formRef = ref();
const confirmLoading = ref(false);

// 是否编辑模式
const isEdit = computed(() => !!props.permission?.id);

// 菜单树选中的节点
const selectedMenuKeys = ref<number[]>([]);
// 菜单树展开的节点
const expandedMenuKeys = ref<number[]>([]);
// 搜索关键词
const searchKeyword = ref('');

// 过滤后的菜单树数据
const displayMenuTreeData = computed(() => {
  if (!searchKeyword.value.trim()) {
    return props.menuTree;
  }

  const keyword = searchKeyword.value.toLowerCase().trim();

  // 递归过滤节点
  function filterNodes(nodes: RoleMenuTreeNode[]): RoleMenuTreeNode[] {
    const result: RoleMenuTreeNode[] = [];

    for (const node of nodes) {
      // 检查当前节点是否匹配
      const isMatch = node.menuName.toLowerCase().includes(keyword);

      // 递归过滤子节点
      const filteredChildren = node.children ? filterNodes(node.children) : [];

      // 如果当前节点匹配，或者有匹配的子节点，则保留
      if (isMatch || filteredChildren.length > 0) {
        result.push({
          ...node,
          children: filteredChildren.length > 0 ? filteredChildren : node.children,
        });
      }
    }

    return result;
  }

  return filterNodes(props.menuTree);
});

// 表单数据
const formData = reactive<Permission>({
  id: undefined,
  permissionCode: '',
  permissionName: '',
  permissionType: PermissionType.URL,
  url: undefined, // 改为 undefined
  method: undefined, // 改为 undefined
  menuId: undefined,
});

// 表单验证规则
const rules: Record<string, Rule[]> = {
  permissionCode: [
    { required: true, message: '请输入权限编码', trigger: 'blur' }
  ],
  permissionName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
  ],
  permissionType: [
    { required: true, message: '请选择权限类型', trigger: 'change' },
  ],
  url: [
    {
      required: false, // 改为非必填
      message: '请输入接口地址',
      trigger: 'blur',
      validator: (_rule: Rule, value: string) => {
        // 接口权限必须填写接口地址
        if (formData.permissionType === PermissionType.URL && !value) {
          return Promise.reject('接口权限必须填写接口地址');
        }
        // 按钮权限可选填写
        return Promise.resolve();
      },
    },
  ],
  method: [
    {
      required: false, // 改为非必填
      message: '请选择请求方法',
      trigger: 'change',
      validator: (_rule: Rule, value: string) => {
        // 接口权限必须选择请求方法
        if (formData.permissionType === PermissionType.URL && !value) {
          return Promise.reject('接口权限必须选择请求方法');
        }
        // 按钮权限可选选择
        return Promise.resolve();
      },
    },
  ],
};

// 菜单树选择事件
function onMenuSelect(selectedKeys: number[], info: any) {
  console.log('🔍 菜单选择事件触发:', {
    selectedKeys,
    info,
    currentSelectedMenuKeys: selectedMenuKeys.value,
  });

  if (selectedKeys.length > 0) {
    // 单击选中
    const selectedId = selectedKeys[0];
    // 如果点击的是已选中的节点，取消选择
    if (selectedMenuKeys.value.includes(selectedId)) {
      console.log('🔄 取消选择菜单:', selectedId);
      selectedMenuKeys.value = [];
      formData.menuId = undefined;
      // 清空菜单时，如果不是编辑模式，也清空权限编码和权限类型
      if (!isEdit.value) {
        formData.permissionCode = '';
        // 恢复默认权限类型为接口权限
        formData.permissionType = PermissionType.URL;
      }
    } else {
      console.log('✅ 选择菜单:', selectedId);
      selectedMenuKeys.value = [selectedId];
      formData.menuId = selectedId;

      // 自动带入菜单的权限编码和权限类型
      const selectedMenu = findMenuById(props.menuTree, selectedId);
      console.log('🔍 查找到的菜单节点:', selectedMenu);
      console.log('🔍 菜单节点的所有字段:', Object.keys(selectedMenu || {}));

      if (selectedMenu) {
        // 1. 自动带入权限编码
        if (selectedMenu.permissionCode) {
          console.log('✅ 自动带入权限编码:', selectedMenu.permissionCode);
          formData.permissionCode = selectedMenu.permissionCode;
        } else {
          console.warn('⚠️ 菜单节点没有 permissionCode 字段');
          console.warn('⚠️ 可用字段列表:', Object.keys(selectedMenu));

          // 临时方案：检查是否有其他可能的权限编码字段
          const possibleFields = ['permission', 'code', 'perms', 'permCode'];
          for (const field of possibleFields) {
            if ((selectedMenu as any)[field]) {
              console.log(`✅ 找到替代字段 ${field}:`, (selectedMenu as any)[field]);
              formData.permissionCode = (selectedMenu as any)[field];
              break;
            }
          }
        }

        // 2. 根据菜单类型自动选择权限类型
        if (selectedMenu.menuType) {
          // menuType: 1-目录, 2-菜单, 3-按钮
          if (selectedMenu.menuType === 1 || selectedMenu.menuType === 2) {
            // 目录或菜单 -> 接口权限
            formData.permissionType = PermissionType.URL;
            console.log('✅ 自动选择权限类型: 接口权限 (目录/菜单)');
          } else if (selectedMenu.menuType === 3) {
            // 按钮 -> 按钮权限
            formData.permissionType = PermissionType.BUTTON;
            console.log('✅ 自动选择权限类型: 按钮权限 (按钮)');
          }
        }
      } else {
        console.error('❌ 未找到菜单节点');
      }
    }
  } else {
    // 取消选择
    console.log('🔄 清空菜单选择');
    selectedMenuKeys.value = [];
    formData.menuId = undefined;
  }

  console.log('📝 菜单选择变化后的状态:', {
    selectedKeys: selectedMenuKeys.value,
    menuId: formData.menuId,
    permissionCode: formData.permissionCode,
    permissionType: formData.permissionType,
    permissionTypeName: formData.permissionType === PermissionType.URL ? '接口权限' : '按钮权限',
  });
}

// 根据ID查找菜单节点
function findMenuById(nodes: RoleMenuTreeNode[], id: number): RoleMenuTreeNode | null {
  for (const node of nodes) {
    if (node.id === id) {
      return node;
    }
    if (node.children && node.children.length > 0) {
      const found = findMenuById(node.children, id);
      if (found) return found;
    }
  }
  return null;
}

// 清空菜单选择
function clearMenuSelection() {
  selectedMenuKeys.value = [];
  formData.menuId = undefined;
  // 清空菜单时，如果不是编辑模式，也清空权限编码和权限类型（允许用户重新输入）
  if (!isEdit.value) {
    formData.permissionCode = '';
    // 恢复默认权限类型为接口权限
    formData.permissionType = PermissionType.URL;
  }
}

// 获取选中的菜单名称
function getSelectedMenuName(): string {
  if (selectedMenuKeys.value.length === 0) return '';

  const selectedId = selectedMenuKeys.value[0];

  function findMenuName(nodes: RoleMenuTreeNode[]): string {
    for (const node of nodes) {
      if (node.id === selectedId) {
        return node.menuName;
      }
      if (node.children && node.children.length > 0) {
        const found = findMenuName(node.children);
        if (found) return found;
      }
    }
    return '';
  }

  return findMenuName(props.menuTree);
}

// 搜索处理
function handleSearch() {
  // 有搜索关键词时，自动展开所有匹配的节点
  if (searchKeyword.value.trim()) {
    expandedMenuKeys.value = extractAllMenuIds(displayMenuTreeData.value);
  }
}

// 监听搜索关键词变化
watch(searchKeyword, (newKeyword) => {
  if (newKeyword.trim()) {
    // 有搜索关键词时，展开所有匹配的节点
    expandedMenuKeys.value = extractAllMenuIds(displayMenuTreeData.value);
  } else {
    // 清空搜索时，恢复默认展开状态
    expandedMenuKeys.value = extractAllMenuIds(props.menuTree);
  }
});

// 提取所有菜单ID（用于展开）
function extractAllMenuIds(menus: RoleMenuTreeNode[]): number[] {
  const ids: number[] = [];
  function traverse(nodes: RoleMenuTreeNode[]) {
    for (const node of nodes) {
      ids.push(node.id);
      if (node.children && node.children.length > 0) {
        traverse(node.children);
      }
    }
  }
  traverse(menus);
  return ids;
}

// 监听弹窗显示
watch(
  () => props.visible,
  (val) => {
    if (val) {
      console.log('🔍 弹窗打开 - 菜单树数据:', {
        '菜单树长度': props.menuTree.length,
        '菜单树数据': props.menuTree,
      });

      // 清空搜索关键词
      searchKeyword.value = '';

      // 默认展开所有节点
      expandedMenuKeys.value = extractAllMenuIds(props.menuTree);

      if (props.permission) {
        // 编辑模式
        Object.assign(formData, props.permission);

        // 确保 menuId 是数字类型
        if (formData.menuId) {
          formData.menuId = Number(formData.menuId);
          // 设置选中的菜单
          selectedMenuKeys.value = [formData.menuId];
        } else {
          selectedMenuKeys.value = [];
        }

        console.log('📝 编辑权限 - 详细调试:', {
          '权限数据': props.permission,
          '菜单ID': formData.menuId,
          '选中的菜单': selectedMenuKeys.value,
          '菜单树数量': props.menuTree.length,
        });
      } else {
        // 新增模式
        resetForm();
      }
    }
  },
);

// 重置表单
function resetForm() {
  formData.id = undefined;
  formData.permissionCode = '';
  formData.permissionName = '';
  formData.permissionType = PermissionType.URL;
  formData.url = undefined;
  formData.method = undefined;
  formData.menuId = undefined;
  selectedMenuKeys.value = [];
  searchKeyword.value = '';
  formRef.value?.clearValidate();
}

// 确定
async function handleOk() {
  try {
    await formRef.value?.validate();
    confirmLoading.value = true;

    if (isEdit.value) {
      // 编辑：移除审计字段
      await updatePermissionApi(prepareUpdateData(formData) as Permission);
      message.success('编辑成功');
    } else {
      // 新增：移除审计字段和 id
      await addPermissionApi(prepareCreateData(formData) as Permission);
      message.success('新增成功');
    }

    emit('success');
    handleCancel();
  } catch (error: any) {
    if (error?.errorFields) {
      // 表单验证错误
      return;
    }
    message.error(error?.msg || '操作失败');
  } finally {
    confirmLoading.value = false;
  }
}

// 取消
function handleCancel() {
  emit('update:visible', false);
  resetForm();
}
</script>

<style scoped lang="scss">
.menu-tree-container {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  padding: 12px;
  background: linear-gradient(to bottom, #fafafa, #f5f5f5);

  /* 选中状态提示 */
  .selected-status-badge {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 14px;
    background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
    border: 2px solid #1890ff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
    animation: slideDown 0.3s ease-out;

    .selected-menu-name {
      padding: 2px 10px;
      background: white;
      border-radius: 4px;
      font-weight: 600;
      color: #1890ff;
      font-size: 13px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    }
  }

  /* 未选择状态提示 */
  .unselected-status-badge {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 14px;
    background: #fafafa;
    border: 1px dashed #d9d9d9;
    border-radius: 8px;
    font-size: 13px;
  }

  .tree-wrapper {
    max-height: 350px;
    overflow-y: auto;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    padding: 8px;
    background: #ffffff;

    /* 自定义滚动条 */
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 3px;

      &:hover {
        background: #a8a8a8;
      }
    }
  }

  .empty-tree {
    padding: 40px 20px;
    text-align: center;
  }
}

.form-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
  line-height: 1.6;
  display: flex;
  align-items: flex-start;
  gap: 4px;

  svg {
    flex-shrink: 0;
    margin-top: 2px;
    color: #1890ff;
  }

  code {
    padding: 2px 6px;
    background: #f5f5f5;
    border: 1px solid #e8e8e8;
    border-radius: 3px;
    font-family: 'Courier New', monospace;
    color: #d63384;
  }
}

/* 菜单节点包装器 */
.menu-node-wrapper {
  display: inline-flex;
  align-items: center;
  padding: 4px 8px;
  border-radius: 6px;
  transition: all 0.3s ease;
  position: relative;

  /* 选中状态 */
  &.is-selected {
    background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
    border: 2px solid #1890ff;
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
    padding: 4px 12px;

    .menu-name {
      color: #1890ff;
      font-weight: 600;
    }
  }

  /* 悬停效果 */
  &:hover:not(.is-selected) {
    background-color: #f5f5f5;
    cursor: pointer;
  }
}

/* 选中的图标动画 */
.menu-icon-wrapper {
  &.selected-icon {
    animation: iconPulse 0.6s ease-in-out;

    span {
      box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
      transform: scale(1.1);
    }
  }
}

/* 选中的按钮样式 */
.selected-button {
  border: 2px solid #52c41a !important;
  background: linear-gradient(to right, #d9f7be, #b7eb8f) !important;
  color: #389e0d !important;
  font-weight: 600 !important;
  box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3) !important;
}

/* 选中标记 */
.selected-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-left: 8px;
  color: #1890ff;
  animation: badgeFadeIn 0.3s ease-in-out;

  svg {
    filter: drop-shadow(0 2px 4px rgba(24, 144, 255, 0.3));
  }
}

/* 动画 */
@keyframes iconPulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.15);
  }
  100% {
    transform: scale(1.1);
  }
}

@keyframes badgeFadeIn {
  0% {
    opacity: 0;
    transform: scale(0.5);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes slideDown {
  0% {
    opacity: 0;
    transform: translateY(-10px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

/* Tree 节点选中样式（覆盖默认样式） */
:deep(.ant-tree-node-selected) {
  background-color: transparent !important;
}

/* Tree 节点悬停样式 */
:deep(.ant-tree-node-content-wrapper) {
  &:hover {
    background-color: transparent !important;
  }
}

/* Tree 标题样式 */
:deep(.ant-tree-title) {
  width: 100%;
}

.permission-examples {
  font-size: 13px;

  p {
    margin-bottom: 8px;
  }

  ul {
    margin: 8px 0;
    padding-left: 20px;

    li {
      margin-bottom: 4px;
      line-height: 1.8;
    }
  }

  code {
    padding: 2px 6px;
    background: #f0f0f0;
    border-radius: 3px;
    font-family: 'Courier New', monospace;
    color: #d63384;
  }

  strong {
    color: #1890ff;
  }
}
</style>

